/*
 * @(#)CommonUtil.java $version 2012-3-5
 * 
 * Copyright 2011 NADOSTAR Gruop. All rights Reserved.
 * NADOSTAR PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nadostar.extensions;

import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;

import com.nadostar.extensions.util.DataMap;

/**
 * @author Lixing
 *
 */
public class CommonUtil {
	private static Log log = LogFactory.getLog(CommonUtil.class);
	
	/**
	 * 마지막으로 일치하는 string replacement.
	 * 
	 * @param ori the ori
	 * @param oStr the o str
	 * @param nStr the n str
	 * @return the string
	 */
	public static String replaceLast(String ori, String oStr, String nStr) {
		String result = "";

		if (StringUtils.isNotEmpty(ori)) {
			result = StringUtils.substring(ori, 0, StringUtils.lastIndexOf(ori, oStr));
			result += nStr;
		}

		return result;
	}
	
	/**
	 * 소수점 반올림.
	 * 
	 * @param infval the infval
	 * @param step the step
	 * @return the float
	 * @return
	 */
	public static float roundDecimal(float infval, int step) {
		return (float)(Math.round(infval * Math.pow(10, step)) / (Math.pow(10, step)));
	}
	
	public static int calcOffset(int page, int pageSize) {
		return (page - 1) * pageSize;
	}
	
	public static int calcRownum(int page, int total, int pageSize) {
		return (page > 1) ? total - (pageSize * (page - 1)) : total;
	}
	
	public static String getActionName(HttpServletRequest request) {
		String uri = request.getRequestURI();
		String subUri = StringUtils.substringAfterLast(uri, "/");
		String actionName = StringUtils.substringBeforeLast(subUri, ".");
		log.debug("@@@@@@@@@@@@@@@@  actionName: " + actionName);
		return actionName;
	}
	
	public static List<DataMap> makeXML2List(String xml) {

		List<DataMap> list = null;

		try {
			Document doc = makeString2Document(xml);

			if( doc == null )
				return null;

			org.jdom.Element rootElement = doc.getRootElement();
			List trList = rootElement.getChildren("TR");
			if( trList == null ) {
				log.warn(">>> Warning in CommonUtil.makeXML2List ::: 어라 TR Element 가 없네...");
				return list;
			}

			list = makeDocument2List(trList, doc);

			log.debug("list.size = " + list.size());
		} catch(Exception e) {
			log.error(">>> Exception in CommonUtil.makeXML2List ::: " + e);
		}

		return list;
	}
	
	public static Document makeString2Document(String xml) {

		Document doc = null;

		try {
			Reader characterStream = new StringReader(StringUtil.replaceStr(StringUtil.trimString(xml), "&", "&amp;"));
			SAXBuilder builder = new SAXBuilder();
			doc = builder.build(characterStream);

			//debugXml(doc);
		} catch(Exception e) {
			log.error(">>> Exception in CommonUtil.makeString2Document ::: " + e);
		}

		return doc;
	}
	
	public static org.dom4j.Document convertList2FGridXml(List<DataMap> list) {
		//if( list == null || list.size() <= 0 )
		//	return null;
		
		
		//log.debug(">>> keys.length = " + keys.length);
		org.dom4j.Document doc = DocumentHelper.createDocument();


		org.dom4j.Element rootElement = doc.addElement("SHEET");
		org.dom4j.Element dataElement = rootElement.addElement("DATA");
		org.dom4j.Element trElement = null;
		
		if( list != null && list.size() > 0 ) {
			String[] keys = getKeys(list.get(0));
			
			DataMap map = null;
			
			for( int i = 0; i < list.size(); i++ ) {
				map = list.get(i);
				
				if( map == null ) continue;
				
				trElement = dataElement.addElement("TR");
				makeChildElements(trElement, map, keys);
			}
		}

		return doc;
	}
	
	public static String[] getKeys(DataMap map) {

		String[] keys = null;
		Vector vect = new Vector();
		Iterator iter = map.keySet().iterator();
		while(iter.hasNext()) {
			vect.addElement(iter.next());
		}
		
		return (String[]) vect.toArray(new String[0]);
	}
	
	private static void makeChildElements(Element e, DataMap map, String[] keys) {
		Element childElement = null;
		
		for( int i = 0; i < keys.length; i++ ) {
			childElement = e.addElement(keys[i]);
			if( map.get(keys[i]) == null ) 
				childElement.addText("");
			else
				childElement.addText(map.getString(keys[i]));
		}
	}
	
	private static List<DataMap> makeDocument2List(List trList, Document doc) {

		List<DataMap> list = new ArrayList();
		org.jdom.Element currentElement = null;

		for( int l = 0; l < trList.size(); l++ ) {
			currentElement = (org.jdom.Element) trList.get(l);

			DataMap dmap = new DataMap();
			Iterator iter = (currentElement.getChildren()).iterator();
			while(iter.hasNext()) {
				org.jdom.Element ele = (org.jdom.Element)iter.next();
				if(ele.getText() != null && ele.getText().trim().indexOf("&amp;") > -1) {
					dmap.put(ele.getName(), ele.getText()==null?"":ele.getText().trim().replace("&amp;", "&"));
				} else {
					dmap.put(ele.getName(), ele.getText()==null?"":ele.getText().trim());
				}
			}

			list.add(dmap);
		}

		return list;
	}
}
